package cn.eonshine.cuba.inf.common.http;


import java.io.IOException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.UnrecoverableKeyException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.util.List;
import java.util.Map;

import com.google.common.collect.Maps;

import cn.eonshine.cuba.inf.common.cert.ReadP12Cert;
import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;

public class ClientUtil {

	/**
	 * 发送Json对象数据
	 * @param url 接口地址
	 * @param content 内容加密后的json数据，数据格式必须是JSON，服务端的接收参数必须用@RequestBody注解
	 * @return HttpResponse
	 */
	public static HttpResponse postJsonBodyData(String url, String content) {
		Map<String, String> headers = Maps.newHashMap();
		headers.put("content-type", "application/json;charset=utf-8");
		headers.put("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:50.0) Gecko/20100101 Firefox/50.0"); 
		HttpResponse resp = postBasicData(url, content, headers);
		return resp;
	}

	/**
	 * 发送对象数据
	 * @param url 接口地址
	 * @param content body内容字符串
	 * @param header 自定义头信息
	 * @return HttpResponse
	 */
	public static HttpResponse postBasicData(String url, String content, Map<String, String> header) {
		HttpRequest req = HttpRequest.post(url).body(content);
		for(Map.Entry<String, String> entry : header.entrySet()) {
			req.header(entry.getKey(), entry.getValue());
		}
		return req.execute();
	}
	
	/**
	 * 发送对象数据
	 * @param url 接口地址
	 * @param content body内容字符串
	 * @param header 自定义放标题头
	 * @param isOverride 是否覆盖已有头信息
	 * @return HttpResponse
	 */
	public static HttpResponse postBasicData(String url, String content, Map<String, List<String>> header, boolean isOverride) {
		HttpRequest req = HttpRequest.post(url).body(content);
		req.header(header, isOverride);
		return req.execute();
	}

	
	
	
	public static void main(String[] args) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException, UnrecoverableKeyException {
		final String KEYSTORE_FILE     = "C:/test/demoCA/certs/ceshiclient.p12";
		 
        final String KEYSTORE_PASSWORD = "123456";
		
		
		KeyStore ks = ReadP12Cert.getKeyStore(KEYSTORE_FILE, KEYSTORE_PASSWORD);

        PrivateKey prikey = ReadP12Cert.getPrivateKey(ks, KEYSTORE_PASSWORD);
        
        Certificate cert = ReadP12Cert.getCertificate(ks);
        
        PublicKey pubkey = cert.getPublicKey();
        
        String clientPubKey = Base64.encode(pubkey.getEncoded());
        
        System.out.println("client pub key = "+clientPubKey);
        
        
		HttpResponse resp1 = postJsonBodyData("http://localhost:8080/securityKey/getPublicKeyBase64", null);
		Message serverPubKey=null;
		if(resp1.getStatus() == 200) {
			serverPubKey = JSONUtil.toBean(resp1.body(), Message.class);
			System.out.println("server PubKey = "+serverPubKey);
		}
		
		// getServerEncryptInfo()
		// 用服务器端的PubKey加密本地客户端公钥证书数据，加密后的数据传输到服务端
		RSA serverRsa = SecureUtil.rsa(null, serverPubKey.getPubKey());
		String transClientPubKey = Base64.encode(serverRsa.encrypt(clientPubKey, KeyType.PublicKey));
		System.out.println("trans client pub key = "+transClientPubKey);
		
        Message message = new Message();
        message.setPubKey(transClientPubKey);
        
		String json = JSONUtil.toJsonStr(message);
		

		System.out.println(json);
		System.out.println("================");
		HttpResponse resp = postJsonBodyData("http://localhost:8080/oil/list", json);
		// 从服务端获取查询结果数据，查询结果采用客户端公钥进行加密，需要客户端的私钥进行解密后在处理
		String result2 = resp.body();
		Message serverMessage = JSONUtil.toBean(result2, Message.class);
		// 开始解密
		System.out.println(serverMessage);
		
		if(serverMessage.getCount()>0) {
			// getClientTransPubKey()
			String msg = serverMessage.getMsg();
			RSA clientRsa = SecureUtil.rsa(prikey.getEncoded(), null);
			String msgaaa = StrUtil.str(clientRsa.decrypt(Base64.decode(msg), KeyType.PrivateKey), CharsetUtil.UTF_8);
			
			System.out.println(msgaaa);
		}
	}
}
